package com.jgraves.WikiToSpeech;


import java.nio.charset.Charset;
import java.util.Arrays;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.TextView;

/**
 * An example of how to use the NFC foreground dispatch APIs. This will intercept any MIME data
 * based NDEF dispatch as well as all dispatched for NfcF tags.
 */
public class ReadNFC extends Activity {
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private TextView mText;
    private int mCount = 0;

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);

        setContentView(R.layout.foreground_dispatch);
        mText = (TextView) findViewById(R.id.text);
        mText.setText("Scan a tag");

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        
//        E/NfcService(  195): No tag fallback activity found for Intent { act=android.nfc.action.TAG_DISCOVERED flg=0x10000000 (has extras) }
//        W/NfcService(  195): Dispatch override registered, but no filters matched
//        I/ActivityManager(  110): Starting: Intent { act=android.nfc.action.NDEF_DISCOVERED dat=http://johngraves.pagekite.me flg=0x10000000 (has extras) } from pid 195
//        I/ActivityManager(  110): Starting: Intent { flg=0x10000000 cmp=com.android.nfc3/com.android.nfc.TechListChooserActivity (has extras) } from pid 195
//        I/ActivityManager(  110): Displayed com.android.nfc3/com.android.nfc.TechListChooserActivity: +226ms


        // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
        // will fill in the intent with the details of the discovered tag before delivering to
        // this activity.
        mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // Setup an intent filter for all MIME based dispatches (android.nfc.action.NDEF_DISCOVERED)
//        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
//        try {
//            ndef.addDataType("text/plain");    
//        }
//        catch (MalformedMimeTypeException e) {
//            throw new RuntimeException("fail", e);
//        }
        mFilters = new IntentFilter[] {
                ndef,
        };

        // Setup a tech list for all NfcF tags
        mTechLists = new String[][] { new String[] { NfcA.class.getName() } };
    }

    @Override
    public void onResume() {
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
    }

    @Override
    public void onNewIntent(Intent intent) {
        // Parse the intent
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
            // When a tag is discovered we send it to the service to be save. We
            // include a PendingIntent for the service to call back onto. This
            // will cause this activity to be restarted with onNewIntent(). At
            // that time we read it from the database and view it.
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
                // Parse the first message in the list
                NdefRecord[] record = msgs[0].getRecords();
                byte[] payload = record[0].getPayload();
                String fullUri = "http://" + new String(Arrays.copyOfRange(payload, 1, payload.length), Charset.forName("UTF-8")) ;
				Intent i = new Intent(ReadNFC.this, InputView.class);
				i.putExtra(Constants.EXTRA_INPUT_STRING, fullUri);
				i.putExtra(Constants.EXTRA_INPUT_TYPE, Constants.HTML_ETHERPAD);
				startActivity(i);
                /*
                 * payload[0] contains the URI Identifier Code, per the
                 * NFC Forum "URI Record Type Definition" section 3.2.2.
                 *
                 * payload[1]...payload[payload.length - 1] contains the rest of
                 * the URI.
                 */
//                String prefix = URI_PREFIX_MAP.get(payload[0]);
//                byte[] fullUri =
//                    Bytes.concat(prefix.getBytes(Charset.forName("UTF-8")), Arrays.copyOfRange(payload, 1,
//                        payload.length));
//                Uri uri = Uri.parse(new String(fullUri, Charset.forName("UTF-8")));

            } else {
                // Unknown tag type
                byte[] empty = new byte[] {};
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }
        } else {
            finish();
            return;
        }
        mText.setText("Discovered tag " + ++mCount + " with intent: " + intent);
    }

    @Override
    public void onPause() {
        super.onPause();
        mAdapter.disableForegroundDispatch(this);
    }
    
}
